#include <glib.h>
#include <string.h>

#define LETTERS "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"


#define URI_RESERVED_CHARS_SUBCOMPONENT_DELIMITERS  "!$&'()*+,;="
#define URI_RESERVED_CHARS_GENERIC_DELIMITERS ":/?#[]@"
#define URI_RESERVED_CHARS_ALLOWED_IN_PATH_ELEMENT URI_RESERVED_CHARS_SUBCOMPONENT_DELIMITERS ":@"
#define URI_RESERVED_CHARS_ALLOWED_IN_PATH URI_RESERVED_CHARS_ALLOWED_IN_PATH_ELEMENT "/"
#define URI_RESERVED_CHARS_ALLOWED_IN_USERINFO URI_RESERVED_CHARS_SUBCOMPONENT_DELIMITERS ":"

#define URI_ALLOWED_SUBCOMPONENT URI_RESERVED_CHARS_SUBCOMPONENT_DELIMITERS LETTERS

gchar* uri_parse_scheme(gchar* uri){
	int i = 0;
	gchar* ret;
	while ( uri[i] != ':'){
		if (!strchr(URI_ALLOWED_SUBCOMPONENT,uri[i])){
			return NULL;
		}
		if (!uri[i]){
			return NULL;
		}
		i++;
	}
	ret = g_malloc(i);
	strncpy(ret,uri,i);
	ret[i]='\0';
	return ret;

}

gchar* uri_escape_string(gchar* uri, gchar* reserved1, int reserved2){
	int spaces = 0,i,j;
	gchar* ret;
	for(i = 0; uri[i]; i++){
		if (uri[i] == ' ') spaces++;
	}
	ret = g_malloc(strlen(uri) + spaces*2 + 1);
	for (i = 0,j = 0; uri[i]; i++,j++){
		
		if (uri[i] == ' '){
			ret[j] ='%';
			ret[++j] ='2';
			ret[++j] = '0';
		}
		else
			ret[j] = uri[i];
	}
	ret[j]='\0';
	return ret;
	

}

